<template>
  <div class="report-generation">
    <el-card class="box-card" v-if="currentReport">
      <div slot="header" class="clearfix">
        <span>故障诊断报告摘要</span>
        <el-button style="float: right;" type="primary" @click="exportDialogVisible = true">导出报告</el-button>
      </div>
      <el-row :gutter="20">
        <el-col :span="6"><b>故障发生时间：</b>{{ currentReport.time }}</el-col>
        <el-col :span="6"><b>故障类型：</b>{{ currentReport.type }}</el-col>
        <el-col :span="6"><b>故障位置：</b>{{ currentReport.position }}</el-col>
        <el-col :span="6"><b>健康度评分：</b>{{ currentReport.score }}</el-col>
      </el-row>
      <el-row style="margin-top: 10px;">
        <el-button type="text" @click="showDetail = !showDetail">{{ showDetail ? '收起详情' : '详情展开' }}</el-button>
      </el-row>
      <el-collapse v-model="showDetailArr">
        <el-collapse-item name="1">
          <template slot="title">故障详情</template>
          <el-row :gutter="20">
            <el-col :span="8">
              <b>特征描述：</b>{{ currentReport.featureDesc }}
            </el-col>
            <el-col :span="8">
              <b>推荐维修策略：</b>{{ currentReport.repairStrategy }}
            </el-col>
            <el-col :span="8">
              <b>所需备件：</b>
              <el-tag v-for="item in currentReport.spareParts" :key="item" style="margin-right: 4px;">{{ item }}</el-tag>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px;">
            <el-col :span="12">
              <b>历史趋势对比图：</b>
              <div ref="trendChart" style="width: 100%; height: 260px;"></div>
            </el-col>
            <el-col :span="12">
              <b>维修流程图：</b>
              <img :src="repairFlowImg" alt="维修流程图" style="width: 100%; max-width: 320px;" />
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-card>

    <el-dialog title="导出报告" :visible.sync="exportDialogVisible" width="400px">
      <el-radio-group v-model="exportType">
        <el-radio label="pdf">PDF</el-radio>
        <el-radio label="excel">Excel</el-radio>
      </el-radio-group>
      <div style="margin: 16px 0;">
        <el-checkbox v-model="withSignature">包含数字签名</el-checkbox>
        <el-checkbox v-model="withTimestamp">包含时间戳</el-checkbox>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exportDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleExport">导 出</el-button>
      </span>
    </el-dialog>

    <el-card class="box-card" style="margin-top: 24px;">
      <div slot="header" class="clearfix">
        <span>历史报告</span>
        <el-button style="float: right;" type="success" @click="handleBatchPrint" :disabled="!multipleSelection.length">批量打印</el-button>
        <el-button style="float: right; margin-right: 8px;" type="warning" @click="handleBatchMail" :disabled="!multipleSelection.length">邮件推送</el-button>
      </div>
      <el-form :inline="true" :model="filter" class="demo-form-inline">
        <el-form-item label="设备">
          <el-input v-model="filter.position" placeholder="如Z轴电机" size="small" />
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker v-model="filter.time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="small" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="filterReports">筛选</el-button>
          <el-button size="small" @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="filteredReports" border style="width: 100%; margin-top: 10px;" @selection-change="handleSelectionChange" ref="reportTable">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="time" label="时间" width="160"></el-table-column>
        <el-table-column prop="type" label="类型" width="120"></el-table-column>
        <el-table-column prop="position" label="位置" width="120"></el-table-column>
        <el-table-column prop="score" label="健康度评分" width="100"></el-table-column>
        <el-table-column prop="featureDesc" label="特征描述"></el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewReport(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="printReport(scope.row)">打印</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { saveAs } from 'file-saver'
import XLSX from 'xlsx'
import jsPDF from 'jspdf'
import 'jspdf-autotable'
import echarts from 'echarts'

export default {
  name: 'FaultDiagnosisReportGeneration',
  data() {
    return {
      // 当前报告
      currentReport: null,
      // 详情展开
      showDetail: false,
      showDetailArr: [],
      // 历史报告
      reports: [],
      filteredReports: [],
      filter: {
        position: '',
        time: []
      },
      multipleSelection: [],
      // 导出
      exportDialogVisible: false,
      exportType: 'pdf',
      withSignature: true,
      withTimestamp: true,
      // 维修流程图
      repairFlowImg: require('@/assets/404_images/404_cloud.png'), // 可替换为实际流程图
    }
  },
  watch: {
    showDetail(val) {
      this.showDetailArr = val ? ['1'] : []
      if (val) this.$nextTick(this.renderTrendChart)
    }
  },
  mounted() {
    this.initMockData()
    this.checkAutoJump()
  },
  methods: {
    // 初始化mock数据和本地存储
    initMockData() {
      let reports = JSON.parse(localStorage.getItem('diagnosisReports') || '[]')
      if (!reports.length) {
        reports = [
          {
            id: 1,
            time: this.formatDate(new Date()),
            type: '主轴不平衡',
            position: 'Z轴电机',
            score: 55,
            featureDesc: '1X频率幅值增大300%',
            trend: [10, 20, 30, 55, 80, 55],
            repairStrategy: '动平衡校正',
            repairFlow: '动平衡→测试→复检',
            spareParts: ['平衡块A型', '螺栓M8'],
            signature: '系统签名',
            timestamp: this.formatDate(new Date()),
            deviceId: 'Z-001',
            email: 'maintain@company.com'
          },
          {
            id: 2,
            time: this.formatDate(new Date(Date.now() - 86400000)),
            type: '轴承磨损',
            position: 'Y轴电机',
            score: 62,
            featureDesc: '高频噪声幅值升高',
            trend: [20, 30, 40, 62, 70, 62],
            repairStrategy: '更换轴承',
            repairFlow: '拆卸→更换→复装',
            spareParts: ['轴承6204'],
            signature: '系统签名',
            timestamp: this.formatDate(new Date(Date.now() - 86400000)),
            deviceId: 'Y-002',
            email: 'maintain@company.com'
          }
        ]
        localStorage.setItem('diagnosisReports', JSON.stringify(reports))
      }
      this.reports = reports
      this.filteredReports = reports
      this.currentReport = reports[0]
    },
    // 检查是否需要自动跳转
    checkAutoJump() {
      // 模拟健康度评分<60且匹配规则库
      const fault = this.reports.find(r => r.score < 60 && r.type === '主轴不平衡')
      if (fault) {
        this.currentReport = fault
        this.$message.success('检测到设备故障，已自动跳转至报告生成页面！')
      }
    },
    // 格式化日期
    formatDate(date) {
      const d = new Date(date)
      return `${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2,'0')}-${d.getDate().toString().padStart(2,'0')} ${d.getHours().toString().padStart(2,'0')}:${d.getMinutes().toString().padStart(2,'0')}`
    },
    // 详情展开趋势图
    renderTrendChart() {
      if (!this.currentReport) return
      const chart = echarts.init(this.$refs.trendChart)
      chart.setOption({
        title: { text: '健康度趋势' },
        tooltip: {},
        xAxis: { data: ['T-5','T-4','T-3','T-2','T-1','当前'] },
        yAxis: {},
        series: [{
          name: '健康度',
          type: 'line',
          data: this.currentReport.trend
        }]
      })
    },
    // 查看报告
    viewReport(row) {
      this.currentReport = row
      this.showDetail = false
      this.$nextTick(() => {
        this.showDetail = true
      })
    },
    // 打印单个报告
    printReport(row) {
      this.exportToPDF(row, true)
    },
    // 批量打印
    handleBatchPrint() {
      this.multipleSelection.forEach(row => this.exportToPDF(row, true))
      this.$message.success('已发送至打印机（模拟）')
    },
    // 批量邮件推送
    handleBatchMail() {
      const emails = this.multipleSelection.map(r => r.email).join(';')
      const subject = encodeURIComponent('设备故障诊断报告')
      const body = encodeURIComponent('请查收设备故障诊断报告。')
      window.open(`mailto:${emails}?subject=${subject}&body=${body}`)
    },
    // 导出报告
    handleExport() {
      if (this.exportType === 'pdf') {
        this.exportToPDF(this.currentReport)
      } else {
        this.exportToExcel(this.currentReport)
      }
      this.exportDialogVisible = false
    },
    // PDF导出
    exportToPDF(report, directPrint = false) {
      const doc = new jsPDF()
      doc.text('设备故障诊断报告', 14, 16)
      doc.autoTable({
        startY: 24,
        head: [['时间','类型','位置','健康度评分']],
        body: [[report.time, report.type, report.position, report.score]]
      })
      doc.autoTable({
        startY: doc.lastAutoTable.finalY + 10,
        head: [['特征描述','维修策略','备件']],
        body: [[report.featureDesc, report.repairStrategy, report.spareParts.join(',')]]
      })
      if (this.withSignature) {
        doc.text(`数字签名：${report.signature}`, 14, doc.lastAutoTable.finalY + 20)
      }
      if (this.withTimestamp) {
        doc.text(`时间戳：${this.formatDate(new Date())}`, 14, doc.lastAutoTable.finalY + 30)
      }
      if (directPrint) {
        doc.autoPrint()
        window.open(doc.output('bloburl'), '_blank')
      } else {
        doc.save(`诊断报告_${report.position}_${report.time}.pdf`)
      }
    },
    // Excel导出
    exportToExcel(report) {
      const ws = XLSX.utils.json_to_sheet([
        {
          时间: report.time,
          类型: report.type,
          位置: report.position,
          健康度评分: report.score,
          特征描述: report.featureDesc,
          维修策略: report.repairStrategy,
          备件: report.spareParts.join(',')
        }
      ])
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '诊断报告')
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `诊断报告_${report.position}_${report.time}.xlsx`)
    },
    // 筛选
    filterReports() {
      this.filteredReports = this.reports.filter(r => {
        const matchPos = !this.filter.position || r.position.includes(this.filter.position)
        let matchTime = true
        if (this.filter.time && this.filter.time.length === 2) {
          const start = new Date(this.filter.time[0]).getTime()
          const end = new Date(this.filter.time[1]).getTime()
          const t = new Date(r.time).getTime()
          matchTime = t >= start && t <= end
        }
        return matchPos && matchTime
      })
    },
    resetFilter() {
      this.filter = { position: '', time: [] }
      this.filteredReports = this.reports
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style scoped>
.report-generation {
  padding: 24px;
}
.box-card {
  margin-bottom: 24px;
}
</style>
